package com.snails.app.utils;

import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import java.lang.ref.WeakReference;

/**
 * @author lawrence
 * @date 2019-05-15 10:57
 */
public class WeakHandler<T> extends Handler {

    public interface HandleMessageListener<V> {
        void handleMessage(@NonNull V param, Message message);
    }

    private WeakReference<T> handlerRef;

    private HandleMessageListener<T> handleMessageListener = null;

    public WeakHandler(T param) {
        this.handlerRef = new WeakReference<>(param);
    }

    public WeakHandler setHandleMessageListener(HandleMessageListener<T> listener) {
        this.handleMessageListener = listener;
        return this;
    }

    @Override
    public void handleMessage(Message message) {
        super.handleMessage(message);
        final T param = handlerRef.get();
        if (handleMessageListener != null && param != null) {
            handleMessageListener.handleMessage(param, message);
        }
    }

}
